﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class MathUtils  {
    public static void SetLayer(GameObject go, int Layer)
    {
        Debug.Log("SetLayer:" + go + ":" + Layer);
        if (go != null)
        {
            var childs = go.GetComponentsInChildren<Transform>();
            foreach (var c in childs)
            {
                c.gameObject.layer = Layer;
            }
        }
    }

    public static void InitGameObject(GameObject go)
    {
        go.transform.localPosition = Vector3.zero;
        go.transform.localRotation = Quaternion.identity;
        go.transform.localScale = Vector3.one;
    }

    /// <summary>
    /// 将copyPart的SkinnedMeshRender中每一根骨骼 在新的Body中找到，并且赋值给新的组建的Render
    /// </summary>
    /// <param name="newPart"></param>
    /// <param name="copyPart"></param>
    /// <param name="root"></param>
    public static void SetBones(GameObject newPart, GameObject copyPart, GameObject root)
    {
        var render = newPart.GetComponent<SkinnedMeshRenderer>();
        var copyRender = copyPart.GetComponent<SkinnedMeshRenderer>();
        var myBones = new Transform[copyRender.bones.Length];
        for (var i = 0; i < copyRender.bones.Length; i++)
        {
            myBones[i] = MathUtils.FindChildRecursive(root.transform, copyRender.bones[i].name);
        }
        render.bones = myBones;
        render.rootBone = MathUtils.FindChildRecursive(root.transform, copyRender.rootBone.name);
    }

    public static Transform FindChildRecursive(Transform t, string name)
    {
        if (t.name == name)
        {
            return t;
        }

        Transform r = t.Find(name);
        if (r != null)
            return r;
        foreach (Transform c in t)
        {
            r = FindChildRecursive(c, name);
            if (r != null)
                return r;
        }
        return null;
    }
}
